/*
 * JCalendar.java
 *
 * Created on August 22, 2008, 3:53 PM
 */

package jp.co.msinet.ui;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.GridLayout;
import java.awt.Label;
import java.util.Calendar;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 *
 * @author  Paul.ch
 */

/**
 *  COULD BE MAKE GENERIC USING JComponent instanceof JTextField / JLabel... 
 */

public class JCalendar extends javax.swing.JDialog {

    /** Creates new form JCalendar */
    public JCalendar(JTextField txt, java.awt.Frame parent, boolean modal, JButton clickedButton) {
        super(parent, modal);
	//processMonthParams(Calendar.getInstance().get(Calendar.YEAR),Calendar.getInstance().get(Calendar.MONTH));
	this.todayYear = Calendar.getInstance().get(Calendar.YEAR);
	this.todayMonth = Calendar.getInstance().get(Calendar.MONTH);
	this.todayDate = Calendar.getInstance().get(Calendar.DATE);
	processMonthParams(this.selectedYear,this.selectedMonth);
        initComponents();
	this.refTextField = txt;

	setBounds(clickedButton.getLocationOnScreen().x,clickedButton.getLocationOnScreen().y,155,205 );
	setVisible(true);
	/**********/

    }

  /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    
    private void initComponents() {
	getContentPane().setLayout(null);
	getContentPane().setBackground(Color.WHITE);
	setResizable(false);

	butPrevious = new JButton("<");
	butPrevious.setBounds(5,5,40,20);
	butPrevious.addMouseListener(new java.awt.event.MouseAdapter() {
	    public void mouseClicked(java.awt.event.MouseEvent evt) {
		butPreviousClicked(evt);
	    }
	});
	add(butPrevious);
	
	butNext = new JButton(">");
	butNext.setBounds(105,5,40,20);
	butNext.addMouseListener(new java.awt.event.MouseAdapter() {
	    public void mouseClicked(java.awt.event.MouseEvent evt) {
		butNextClicked(evt);
	    }
	});
	add(butNext);

	labelYM = new JLabel(this.selectedYear + "/" + (this.selectedMonth+1) );
	labelYM.setHorizontalAlignment(JLabel.CENTER);
	labelYM.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1) ); 
//	labelYM.setOpaque(true);
//	labelYM.setBackground(new Color(189,189,255));
	labelYM.setBounds(50,5,50,20);
	add(labelYM);
	/**********/
	
	for( int i=0;i<7;i++){
	    labelWeeks[i] = new JLabel(this.datesMnemonic[i]);
	    labelWeeks[i].setBounds(10+i*20,35,10,10);
	    add(labelWeeks[i]);
	}
	labelWeeks[0].setForeground(Color.RED);
	
	int DATE_WIDTH	= 15;
	int DATE_HEIGHT = 15;
	for ( int i=0 ; i<labelDates.length ; i++){
	    labelDates[i] = new JLabel("");
	    int col = (i % 7) * 20;
	    int row = i / 7 * 20;
	    labelDates[i].setBounds(7+col, 55+row , DATE_WIDTH, DATE_HEIGHT);
	    labelDates[i].setOpaque(true);
	    labelDates[i].setHorizontalAlignment(JLabel.CENTER);
	    labelDates[i].addMouseListener(new java.awt.event.MouseAdapter() {
		public void mouseClicked(java.awt.event.MouseEvent evt) {
		    jLabelMouseClicked(evt);
		}
	    });
	    if( i%7 == 0 )
		labelDates[i].setForeground(Color.RED);
	    labelDates[i].setCursor(cs);
	    add(labelDates[i]);
	}
	
	PlaceDates();
	pack();
	setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    }

    private void PlaceDates(){
        //JOptionPane.showMessageDialog(null, "PLACE DATE:" + this.startDayOfMonth + ", " + this.daysInMonth);
	int i=0;
	while( i < this.startDayOfMonth - 1){
	    labelDates[i].setVisible(false);
	    i++;
	}
	int totalDates = this.daysInMonth;
	int j = i-1;
	while( totalDates > 0 ){
            labelDates[i].setVisible(true);
	    labelDates[i].setText("" + (i-j) );
	    //System.out.println(this.todayYear + ":" + this.todayMonth + ":" + this.todayDate);
	    setCurrentDate(this.selectedYear, this.selectedMonth,i, i-j);
	    totalDates--;
	    i++;
	}
	while( i < labelDates.length){
	    labelDates[i].setVisible(false);
	    i++;
	}
    }
    
    private void processMonthParams(int year, int month){
	calendar.set(Calendar.YEAR,year);
	calendar.set(Calendar.MONTH,month);
	calendar.set(calendar.DAY_OF_MONTH,1);
	this.daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
	this.startDayOfMonth = calendar.get(Calendar.DAY_OF_WEEK);
    }
    
    private void butNextClicked(java.awt.event.MouseEvent evt){
        if( butNext.isEnabled() ){
            if( this.selectedMonth + 1 >= 12 ){
                this.selectedYear += 1;
                this.selectedMonth = (this.selectedMonth+1)%12;
            } else {
                this.selectedMonth++;
            }
            checkNextPreviousVisibility();
            labelYM.setText(this.selectedYear + "/" + (this.selectedMonth+1) );
            processMonthParams(this.selectedYear,this.selectedMonth);
            showDates();
            PlaceDates();
        }
    }

    private void showDates(){
	System.out.println("YEAR: " + this.selectedYear + " MONTH: " + this.selectedMonth);
    }
    private void butPreviousClicked(java.awt.event.MouseEvent evt){
        if( butPrevious.isEnabled() ){
            if( this.selectedMonth - 1 < 0 ){
                this.selectedYear -= 1;
                this.selectedMonth = 11;	    // 0 Based
            } else {
                this.selectedMonth--;
            }
            checkNextPreviousVisibility();
            labelYM.setText(this.selectedYear + "/" + (this.selectedMonth+1) );
            processMonthParams(this.selectedYear,this.selectedMonth);
            showDates();
            PlaceDates();
        }
    }

    private void checkNextPreviousVisibility(){
        if( this.selectedYear <= this.MIN_YEAR && this.selectedMonth <= 0){
            this.butPrevious.setEnabled(false);
        }else{
            this.butPrevious.setEnabled(true);
        }

        if( this.selectedYear >= this.MAX_YEAR && this.selectedMonth >= 11){
            this.butNext.setEnabled(false);
        } else {
            this.butNext.setEnabled(true);
        }
    }
    private void jLabelMouseClicked(java.awt.event.MouseEvent evt){
	String date = ((JLabel) evt.getSource()).getText();
        String m = ( (this.selectedMonth+1) < 10) ? "0" + ( this.selectedMonth + 1 ) : "" + ( this.selectedMonth + 1 );
	//System.out.println("LENGTH: " + date.length());
        String d = ( date.length() < 2 ) ? "0" + date : "" + date;
	this.refTextField.setText(  this.selectedYear + "/" +  m + "/" + d);
	this.dispose();
    }

    private void setCurrentDate(int selectedYear, int selectedMonth, int i, int date) {
	if( selectedYear == this.todayYear && selectedMonth == this.todayMonth && date == this.todayDate ){
	    this.labelDates[i].setForeground(Color.WHITE);
	    if( i%7 == 0)
		this.labelDates[i].setBackground(Color.RED);
	    else
		this.labelDates[i].setBackground(Color.BLACK);
	} else {
	    
	    this.labelDates[i].setBackground(Color.WHITE);
	    if( i%7 == 0)
		this.labelDates[i].setForeground(Color.RED);
	    else
		this.labelDates[i].setForeground(Color.BLACK);
	}
    }
    
    private JButton	butPrevious;
    private JButton	butNext;
    private JLabel	labelYM;
    private JLabel	labelMonth;
    private JLabel	labelWeeks[] = new JLabel[7];
    private JLabel	labelDates[] = new JLabel[42];
    private JLabel	Slash;
    private Cursor cs = new Cursor(Cursor.HAND_CURSOR);
    private Calendar calendar = Calendar.getInstance();
    private JTextField refTextField;
    
    private int todayYear, todayMonth, todayDate;
    private final static int MAX_YEAR = 2009;
    private final static int MIN_YEAR = 2007;
    private int daysInMonth;
    private int startDayOfMonth;
    private String datesMnemonic[] = {"S","M","T","W","T","F","S"};
    private int selectedMonth = Calendar.getInstance().get(Calendar.MONTH);;
    private int selectedYear = Calendar.getInstance().get(Calendar.YEAR);
    
}
